// utils/api.js
// API 请求封装

const config = require('./config.js')

/**
 * 封装 wx.request
 */
function request(options) {
    return new Promise((resolve, reject) => {
        wx.request({
            url: config.apiBaseUrl + options.url,
            method: options.method || 'GET',
            data: options.data || {},
            header: {
                'content-type': 'application/json',
                'Authorization': wx.getStorageSync('token') || ''
            },
            success: res => {
                if (res.statusCode === 200) {
                    if (res.data.code === 0 || res.data.success) {
                        resolve(res.data.data || res.data)
                    } else {
                        wx.showToast({
                            title: res.data.message || '请求失败',
                            icon: 'none'
                        })
                        reject(res.data)
                    }
                } else {
                    wx.showToast({
                        title: '网络请求失败',
                        icon: 'none'
                    })
                    reject(res)
                }
            },
            fail: err => {
                wx.showToast({
                    title: '网络连接失败',
                    icon: 'none'
                })
                reject(err)
            }
        })
    })
}

/**
 * 用户登录
 */
function login(code) {
    return request({
        url: '/user/login',
        method: 'POST',
        data: { code }
    })
}

/**
 * 保存用户信息
 */
function saveUserInfo(userInfo) {
    return request({
        url: '/user/save',
        method: 'POST',
        data: userInfo
    })
}

/**
 * 获取用户信息
 */
function getUserInfo(openid) {
    return request({
        url: '/user/info',
        method: 'GET',
        data: { openid }
    })
}

/**
 * 创建报修单
 */
function createRepairOrder(data) {
    return request({
        url: '/repair/create',
        method: 'POST',
        data
    })
}

/**
 * 设置用户角色
 */
function setUserRole(data) {
    return request({
        url: '/user/set-role',
        method: 'POST',
        data
    })
}

/**
 * 获取报修单列表
 */
function getRepairOrders(params) {
    return request({
        url: '/repair/list',
        method: 'GET',
        data: params
    })
}

/**
 * 获取报修单详情
 */
function getRepairOrderDetail(orderId) {
    return request({
        url: '/repair/detail',
        method: 'GET',
        data: { orderId }
    })
}

/**
 * 更新报修单状态
 */
function updateRepairOrder(orderId, data) {
    return request({
        url: '/repair/update',
        method: 'POST',
        data: { orderId, ...data }
    })
}

/**
 * 移除维修单备件
 */
function removeSparePart(repairOrderId, partId) {
    return request({
        url: '/repair/remove-spare-part',
        method: 'POST',
        data: { repairOrderId, partId, adminKey: 'repair2024admin' }
    })
}

/**
 * 获取机房信息
 */
function getLabInfo(labId) {
    return request({
        url: '/lab/info',
        method: 'GET',
        data: { labId }
    })
}

/**
 * 获取机房列表
 */
function getLabList() {
    return request({
        url: '/lab/list',
        method: 'GET'
    })
}

/**
 * 上传图片
 */
function uploadImage(filePath) {
    return new Promise((resolve, reject) => {
        wx.uploadFile({
            url: config.uploadUrl,
            filePath: filePath,
            name: 'file',
            header: {
                'Authorization': wx.getStorageSync('token') || ''
            },
            success: res => {
                const data = JSON.parse(res.data)
                if (data.code === 0 || data.success) {
                    resolve(data.data.url || data.url)
                } else {
                    wx.showToast({
                        title: data.message || '上传失败',
                        icon: 'none'
                    })
                    reject(data)
                }
            },
            fail: err => {
                wx.showToast({
                    title: '上传失败',
                    icon: 'none'
                })
                reject(err)
            }
        })
    })
}

/**
 * 批量上传图片
 */
function uploadImages(filePaths) {
    const promises = filePaths.map(filePath => uploadImage(filePath))
    return Promise.all(promises)
}

/**
 * 订阅消息
 */
function subscribeMessage(templateIds) {
    return new Promise((resolve, reject) => {
        wx.requestSubscribeMessage({
            tmplIds: templateIds,
            success: res => {
                resolve(res)
            },
            fail: err => {
                console.log('订阅失败', err)
                reject(err)
            }
        })
    })
}

/**
 * 获取资产详细信息（用于扫码后自动填充）
 */
function getAssetInfo(assetId) {
    return request({
        url: `/assets/${assetId}/info`,
        method: 'GET'
    })
}

module.exports = {
    request,
    login,
    saveUserInfo,
    setUserRole,
    getUserInfo,
    createRepairOrder,
    getRepairOrders,
    getRepairOrderDetail,
    updateRepairOrder,
    removeSparePart,
    getLabInfo,
    getLabList,
    uploadImage,
    uploadImages,
    subscribeMessage,
    getAssetInfo
}
